    export default {
        name: "userMain",
        setup(props) {
            const title = ref('添加用户');
            const dialogBgsx =ref(false);
            const tableData = ref([]);
            const total = ref(0);
        	const model = ref({Username: '', Name: '', Role: '', Phone: '', Email: '', Points: 0});
            const pagesys = ref({page: 1, pageSize: 15, search: ''});
            const userform = ref();
            const fileInput = ref();
            const tid = ref(0);
            const useroption = ref({admin: '总管理员', xmgly: '项目管理员', tby: '填报员', shy: '审核员', user: '普通用户'});
            const selectedRows = ref([]); // 存储选中的行
            
            onMounted(async() => {
                await getdata();
            });
            
            //每页条数改变时触发 选择一页显示多少行
            const handleSizeChange = (val) => {
                pagesys.value.page = 1;
                pagesys.value.pageSize = val;
                getdata();
            };
        
            //翻页
            const handleCurrentChange = (val) => {
                pagesys.value.page = val;
                getdata();
            };
        
            //每页数量改变
            const sizechange = (e) => {
                pagesys.value.pageSize = e;
                getdata();
            };
            
            //获取用户表数据
            const getdata = _.debounce(async() => {
                const res = await getuserlist(pagesys.value);
                tableData.value = res.items;
                total.value = res.total;
            }, 300);
            
            //提交保存
            const submitForm = _.debounce(async() => {
                try {
                    const valid = await userform.value.validate();
                    if (!valid) {
                        return;
                    }
                    if (!window.validators.isMobile(model.value.Phone)) {
                        ElMessage.error('手机号错误');
                        return;
                    }
                    let data = {...model.value};
    				data.ID = tid.value;
    				let err = "";
    				if (!data.Username) err = "用户名为空";
    				if (!data.Name) err = "姓名为空";
    				if (!data.Role) err = "角色为空";
    				if (data.ID == 0 && !data.Password) err = "密码为空"; // 添加时密码验证
    				if (err) return ElMessage.error(err);
                    data.Phone = data.Phone.toString(); // 转换手机号为字符串
                    data.Points = Number(data.Points);
                    delete data.CreatedAt;
                    delete data.UpdatedAt;
                    data.ID == 0 ? await adduser(data) : await updateuser(data);
                    ElMessage.success('保存成功');
                    dialogBgsx.value = false; // 关闭对话框
                    getdata();
                } catch (error) {
                    console.error('表单验证失败:', error);
                    ElMessage.error('表单验证失败，请检查输入');
                }
            }, 500);
            
            //弹窗添加用户
            const addrow = () => {
                title.value = '添加用户';
                tid.value = 0;
                model.value = {Username: '', Name: '', Role: '', Phone: '', Email: '', Points: 0};
                dialogBgsx.value = true;
            }
            
            //弹窗修改用户
            const handleEdit = (row) => {
                title.value = '修改用户';
                model.value = {...row};
                model.value.Password = ''; //密码需要后端加密
                tid.value = row.ID;
                dialogBgsx.value = true;
            }
            
            //批量删除
            const deleteuser = async () => {
                if (!selectedRows.value?.length) {
                    return ElMessage.error('请选择用户');
                }
                // 检查是否包含系统管理员
                const hasAdmin = selectedRows.value.some(row => row.ID == 1);
                if (hasAdmin) {
                    return ElMessage.error('系统默认管理员禁止删除');
                }
                try {
                    // 二次确认
                    const confirmResult = await ElMessageBox.confirm(
                        `确认删除选中的 ${selectedRows.value.length} 个用户？删除后不可恢复`,
                        '警告',
                        { 
                            type: 'warning',
                            confirmButtonText: '确认删除',
                            cancelButtonText: '取消'
                        }
                    );
                    if (confirmResult === 'confirm') {
                        const ids = selectedRows.value.map(row => row.ID);
                        const res = await deluserapi({ ids });
                        ElMessage.success(`成功删除 ${selectedRows.value.length} 个用户`);
                        getdata();
                        selectedRows.value = [];
                    }
                } catch (error) {
                    if (error === 'cancel') {
                        
                    } else {
                        console.error('删除失败:', error);
                        ElMessage.error('删除操作失败，请检查网络或联系管理员');
                    }
                }
            };
        	
        	//删除用户
        	const handleDelete = _.debounce(async (row) => {
        	    if(!row['ID']) return ElMessage.error('用户不存在');
        	    if(row['ID'] == 1) return ElMessage.error('系统默认管理员禁止删除');
                try {
                    const confirmResult = await ElMessageBox.confirm('删除后不可恢复','确认要删除？',{ type: 'warning' });
                    if (confirmResult === 'confirm') {
                        var res = await deluserapi({ids: [row['ID']]});
                        ElMessage.success('删除成功');
                        getdata();
                    } 
                } catch (error) {
                    if (error === 'cancel') {
                        return;
                    }
                    console.error('操作过程中出现错误:', error);
                }
        	}, 500);
        	
            //导出数据，最大10000行
            const exportData = _.debounce(async() => {
                const res = await getuserlist({pageSize: 10000, ...pagesys.value});
                if(total.value > 10000){
                    ElMessage.error('数据表超过10000条，只导出前10000条');
                }
                exportToExcel('用户表', res.items, {Username: '用户名', Name: '姓名', Role: '角色', Email: '邮箱'});
            }, 1000);
            
            // 下载模板
            const downloadTemplate = () => {
                const templateData = [{
                    Username: '示例账号',
                    Name: '张三',
                    Role: '普通用户',
                    Phone: '13800138000',
                    Email: 'demo@example.com',
                    Password: '123456'
                }];
                exportToExcel('用户导入模板', templateData, {
                    Username: '用户名',
                    Name: '姓名',
                    Role: '角色',
                    Phone: '电话',
                    Email: '邮箱',
                    Password: '密码'
                }); 
            }
            
            const selectFile = () => {
                const messageContent = `
                    <small>请先下载模板，按要求的格式录入数据再导入，注意用户名不得出现重复。</small>
                `;
                ElMessageBox.alert(messageContent, '批量导入用户', {
                    confirmButtonText: '上传表格',
                    dangerouslyUseHTMLString: true,
                    callback: (action) => {
                        if(action == 'confirm') fileInput.value.click(); // 触发文件输入框的点击事件
                    }
                });
            }
            
            const readBrowserFile = (file) => {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = e => {
                        const arrayBuffer = e.target.result;
                        resolve(new Uint8Array(arrayBuffer));
                    };
                    reader.onerror = e => reject(e.target.error);
                    reader.readAsArrayBuffer(file); // 保持 ArrayBuffer 读取
                });
            };
            
            // 选择行数据
    		const handleSelectionChange = (rows) => {
    		    selectedRows.value = rows;
    		}
            
            //上传表格解析
			const handleFileChange = async (event) => {
				const file = event.target.files[0];
				if (!file) return;
				const allowedExtensions = /(\.xlsx|\.xls)$/i;
				if (!allowedExtensions.exec(file.name)) {
					ElMessage.error('仅支持Excel文件格式');
					event.target.value = ''; // 重置input
					return;
				}
				try {
					const arrayBuffer = await readBrowserFile(file);
					const workbook = XLSX.read(arrayBuffer, {
						type: 'array',
						cellText: true,
						cellDates: true
					});
					const sheetNames = workbook.SheetNames;
					const worksheet = workbook.Sheets[sheetNames[0]];
					const sheetJSONOpts = {
						raw: false, // 保持原始数据类型（默认为false）
						blankrows: false, // 是否保留空白行 
						defval: '', // 默认值为空字符串
						cellText: true, // 强制将所有单元格内容转换为字符串 
						cellDates: false, // 关闭日期格式转换
						type: 'text' // 指定读取类型为文本
					};
					let data = XLSX.utils.sheet_to_json(worksheet, sheetJSONOpts);
					if (data.length === 0) {
						throw new Error('表格数据为空');
					}
					if (data.length > 5000) {
						throw new Error('单次导入最多5000条');
					}
					const fieldMapping = {
						'用户名': 'Username',
						'姓名': 'Name',
						'角色': 'Role',
						'电话': 'Phone',
						'邮箱': 'Email',
						'密码': 'Password'
					};
					const actualHeaders = Object.keys(data[0]);
					const requiredHeaders = Object.keys(fieldMapping);
					const missingHeaders = requiredHeaders.filter(h => !actualHeaders.includes(h));
					if (missingHeaders.length > 0) {
						throw new Error(`缺少必要列：${missingHeaders.join(', ')}`);
					}
					const processedData = data.map((row, index) => {
						const obj = {};
						for (const [chineseHeader, englishKey] of Object.entries(fieldMapping)) {
							const value = String(row[chineseHeader] || '').trim();
							if (!['Phone', 'Username'].includes(englishKey) && !value) {
								throw new Error(`第 ${index + 1} 行：${chineseHeader} 不能为空`);
							}
							if (englishKey === 'Phone' && value && !/^\d{7,15}$/.test(value)) {
								throw new Error(`第 ${index + 1} 行：电话号码格式错误：${value}`);
							}
							obj[englishKey] = value;
						}
						return obj;
					});
					const res = await importuser(processedData);
					ElMessage.success(`成功导入 ${processedData.length} 个用户`);
					getdata(); // 刷新数据
				} catch (error) {
					ElMessage.error(error.message || '文件处理失败');
				} finally {
					event.target.value = '';
				}
			};
    
            return {
                exportData,
                addrow,
                handleEdit,
                handleDelete,
                tableData,
                dialogBgsx,
                submitForm,
                total,
                model,
                title,
                getdata,
                getuserlist,
                pagesys,
                handleSizeChange,
                handleCurrentChange,
                sizechange,
                adduser,
                updateuser,
                userform,
                fileInput,
                selectFile,
                handleFileChange,
                importuser,
                useroption,
                readBrowserFile,
                tid, selectedRows,handleSelectionChange, deleteuser,
                downloadTemplate
            };
        },
        
        template: `
            <div>
            	<el-dialog v-model="dialogBgsx" :title="title">
            		<el-form :model="model" label-width="100px" ref="userform" label-position="top">
            			<el-form-item label='用户名' prop="Username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
            				<el-input v-model="model.Username" placeholder="请输入用户名" :disabled="title == '修改用户'"></el-input>
            			</el-form-item>
            			<el-form-item label="姓名" prop="Name" :rules="[{ required: true, message: '请输入姓名' }]">
                            <el-input v-model="model.Name" placeholder="输入姓名"></el-input>
                        </el-form-item>
            		    <el-form-item label="角色" prop="Role" :rules="[{ required: true, message: '请选择角色' }]">
            				<el-select v-model="model.Role" clearable placeholder="请选择角色">
            					<el-option v-for="(item, key) in useroption" :key="key" :label="item" :value="key">{{item}}</el-option>
            				</el-select>
            			</el-form-item>
            			<el-form-item label="手机号" prop="Phone" :rules="[{ required: true, message: '请输入手机号' }]">
                            <el-input type="number" v-model="model.Phone" placeholder="输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="Email">
                            <el-input type="text" v-model="model.Email" placeholder="输入邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="积分" prop="Points" :rules="[{ required: true, message: '请输入积分' }]">
                            <el-input-number v-model="model.Points" placeholder="输入手机号"></el-input-number>
                        </el-form-item>
                        <el-form-item label="微信绑定" prop="OpenID">
                            <el-input type="text" v-model="model.OpenID" placeholder="小程序登录自动绑定"></el-input>
                        </el-form-item>
            			<el-form-item label="用户密码" prop="Password" v-if="title=='添加用户'" :rules="[{ required: true, message: '请输入密码' }]">
                            <el-input type="password" v-model="model.Password" placeholder="输入密码"></el-input>
                        </el-form-item>
                        <el-form-item label="用户密码" prop="Password" v-else>
                            <el-input type="password" v-model="model.Password" placeholder="输入密码"></el-input>
                        </el-form-item>
            			<el-row justify="center">
            				<el-col :span="8" style="text-align: center;margin: 20px;">
                                <el-button type="primary" @click="submitForm()">提交</el-button>
                                <el-button @click="dialogBgsx = false">取消</el-button>
            				</el-col>
            			</el-row>
            		</el-form>
            	</el-dialog>
            	
                <el-page-header :icon="null" title="用户管理" content="系统默认管理员不能删除">
                    <div style="color: #484c50;padding:10px 0;font-size:14px;">批量导入用户时，需要先下载excel导入模板。</div>
                </el-page-header>
                <div class="mt-2">
                    <el-button type="primary" @click="addrow()">添加用户</el-button>
                    <el-button type="primary" @click="selectFile()">批量导入</el-button>
                    <el-button type="primary" @click="downloadTemplate()">下载模板</el-button>
                    <el-button type="primary" @click="exportData()" plain>导出用户</el-button>
                    <el-button type="danger" @click="deleteuser()">批量删除</el-button>
                    <el-input style="width:500px;margin-left: 10px;" v-model="pagesys.search" placeholder="输入用户名或姓名查找" clearable @keyup.enter="getdata" @clear="getdata">
                        <template #prefix>
                        	<el-icon class="el-input__icon"><search /></el-icon>
                        </template>
    					<template #append>
                            <el-button @click="getdata">搜索</el-button>
                        </template>
    				</el-input>
                </div>
                <input type="file" ref="fileInput" @change="handleFileChange" accept=".xlsx" style="display: none;">
            
                <el-table :data="tableData" table-layout="auto" :header-cell-style="{'font-size': '14px', background: '#f9f9f9'}" border show-overflow-tooltip :row-key="(row) => row.ID" class="mt-1" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
                    <el-table-column prop="ID" label="ID" align="center" width="80"></el-table-column>
                    <el-table-column sortable prop="Username" label="用户名"></el-table-column>
                    <el-table-column sortable prop="Name" label="姓名"></el-table-column>
                    <el-table-column sortable prop="Role" label="角色" width="100">
                        <template #default="scope">
                            {{ scope.row.Role ? useroption[scope.row.Role] : scope.row.Role }}
                        </template>
                    </el-table-column>
                    <el-table-column sortable prop="Phone" label="手机" width="120"></el-table-column>
                    <el-table-column sortable prop="Email" label="邮箱"></el-table-column>
                    <el-table-column prop="OpenID" label="微信绑定"></el-table-column>
                    <el-table-column sortable prop="Points" label="积分" width="120"></el-table-column>
                    <el-table-column fixed="right" label="操作" :width="140">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleEdit(scope.row)">修改</el-button>
                            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            	<el-pagination background @size-change="sizechange" :page-sizes="[10, 20, 30, 50]" :page-size="pagesys.pageSize" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" :total="total" :current-page.sync="pagesys.page"></el-pagination>
            </div>
        `
    }